/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.storage.lmdb

import java.io.File
import java.nio.ByteBuffer
import javax.inject.Inject
import javax.inject.Named
import org.apache.commons.lang3.StringUtils
import org.eclipse.xtend.lib.annotations.ToString
import org.lmdbjava.Env
import org.slf4j.LoggerFactory

import static org.lmdbjava.ByteBufferProxy.PROXY_OPTIMAL
import javax.inject.Provider

@ToString
class LmdbProvider implements Provider<LmdbDataSource> {
	val static LOG = LoggerFactory.getLogger(LmdbProvider);

	@Inject
	@Named("lmdb.path")
	String path;

	@Inject
	@Named("lmdb.maxSize")
	int maxSize;

	@Inject
	@Named("lmdb.maxDbs")
	int maxDbs;

	@Inject
	@Named("lmdb.maxReaders")
	int maxReaders;

	override get() {
		LOG.info(LmdbProvider.toString());
		if (StringUtils.isNotBlank(path)) {
			var lmdbPath = new File(path);
			var flag = lmdbPath.exists;
			if (!flag) {
				flag = lmdbPath.mkdirs;
			}
			if (flag) {
				var ds = new LmdbDataSource();
				var env = Env.create(PROXY_OPTIMAL).setMapSize(this.maxSize * 1024 * 1024).setMaxDbs(this.maxDbs).
					setMaxReaders(this.maxReaders).open(lmdbPath);
				ds.env = env;
				return ds;
			}
		}
		return null;
	}

}
